﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace IceDog.TaskFactory
{
    public class ThreadFactory
    {
        int workersCount;
        private List<Thread> threads = new List<Thread>();

        public ThreadFactory(int threadCount, int workCount, Action<int, int, string> action)
        {
            workersCount = threadCount;

            int totalWorkLoad = workCount;
            int workLoad = totalWorkLoad / workersCount;
            int extraLoad = totalWorkLoad % workersCount;

            for (int i = 0; i < workersCount; i++)
            {
                int min, max;
                if (i < (workersCount - 1))
                {
                    min = (i * workLoad);
                    max = ((i * workLoad) + workLoad - 1);
                }
                else
                {
                    min = (i * workLoad);
                    max = (i * workLoad) + (workLoad - 1 + extraLoad);
                }
                string name = "Working Thread#" + i;

                Thread worker = new Thread(() => { action(min, max, name); });
                worker.Name = name;
                threads.Add(worker);
            }
        }

        public void StartWorking()
        {
            foreach (Thread thread in threads)
            {
                thread.Start();
            }

            foreach (Thread thread in threads)
            {
                thread.Join();
            }
        }
    }
}
